package com.davy.tx.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

public class DeviceIdHelper {

    // 获取设备唯一ID的主方法
    public static String getDeviceId(Context context) {
        String deviceId = null;

        // 优先使用 ANDROID_ID
        deviceId = getAndroidId(context);
        if (deviceId != null && !deviceId.isEmpty()) {
            Log.d("DeviceIdHelper", "ANDROID_ID: " + deviceId);
            return deviceId;
        }

        // 如果 ANDROID_ID 不可用，使用序列号
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O) {
            deviceId = getDeviceSerial();
            if (deviceId != null && !deviceId.isEmpty()) {
                Log.d("DeviceIdHelper", "SERIAL: " + deviceId);
                return deviceId;
            }
        }

        // 尝试使用 IMEI (需要 READ_PHONE_STATE 权限)
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            deviceId = getIMEI(context);
            if (deviceId != null && !deviceId.isEmpty()) {
                Log.d("DeviceIdHelper", "IMEI: " + deviceId);
                return deviceId;
            }
        }

        Log.d("DeviceIdHelper", "设备ID获取失败");
        return "Unknown";
    }

    // 获取 ANDROID_ID
    private static String getAndroidId(Context context) {
        return Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
    }

    // 获取设备序列号 (适用于 Android 8.0 及以下)
    private static String getDeviceSerial() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O) {
            return Build.SERIAL;
        } else {
            return Build.getSerial();
        }
    }

    // 获取 IMEI 号码 (仅在电话功能设备上有效)
    private static String getIMEI(Context context) {
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
            return telephonyManager.getDeviceId();
        }
        return null;
    }
}
